<template>
    <div class="assignment-management">
        <div class="page-header">
            <h1>作业管理</h1>
            <a-space>
                <a-button type="primary" @click="showAddModal = true">
                    <template #icon>
                        <PlusOutlined />
                    </template>
                    添加作业
                </a-button>
                <a-button @click="generateAIAssignment">
                    <template #icon>
                        <RobotOutlined />
                    </template>
                    AI生成作业
                </a-button>
            </a-space>
        </div>

        <!-- 统计卡片 -->
        <a-row :gutter="16" class="stats-cards">
            <a-col :span="6">
                <a-card>
                    <a-statistic title="总作业数" :value="statistics.totalAssignments" :value-style="{ color: '#1890ff' }">
                        <template #prefix>
                            <FileTextOutlined />
                        </template>
                    </a-statistic>
                </a-card>
            </a-col>
            <a-col :span="6">
                <a-card>
                    <a-statistic title="待批改" :value="statistics.pendingReview" :value-style="{ color: '#faad14' }">
                        <template #prefix>
                            <ClockCircleOutlined />
                        </template>
                    </a-statistic>
                </a-card>
            </a-col>
            <a-col :span="6">
                <a-card>
                    <a-statistic title="已完成" :value="statistics.completed" :value-style="{ color: '#52c41a' }">
                        <template #prefix>
                            <CheckCircleOutlined />
                        </template>
                    </a-statistic>
                </a-card>
            </a-col>
            <a-col :span="6">
                <a-card>
                    <a-statistic title="平均分" :value="statistics.averageScore" :value-style="{ color: '#722ed1' }"
                        suffix="分">
                        <template #prefix>
                            <TrophyOutlined />
                        </template>
                    </a-statistic>
                </a-card>
            </a-col>
        </a-row>

        <!-- 搜索和筛选 -->
        <div class="search-section">
            <a-row :gutter="16">
                <a-col :span="6">
                    <a-input-search v-model:value="searchKeyword" placeholder="搜索作业标题" @search="handleSearch" />
                </a-col>
                <a-col :span="4">
                    <a-select v-model:value="selectedCourse" placeholder="选择课程" style="width: 100%"
                        @change="handleCourseChange">
                        <a-select-option value="">全部课程</a-select-option>
                        <a-select-option value="ai">AI智能体开发实战</a-select-option>
                        <a-select-option value="vue">Vue3实战开发</a-select-option>
                        <a-select-option value="spring">SpringBoot微服务</a-select-option>
                    </a-select>
                </a-col>
                <a-col :span="4">
                    <a-select v-model:value="selectedStatus" placeholder="选择状态" style="width: 100%"
                        @change="handleStatusChange">
                        <a-select-option value="">全部状态</a-select-option>
                        <a-select-option value="active">进行中</a-select-option>
                        <a-select-option value="completed">已结束</a-select-option>
                        <a-select-option value="draft">草稿</a-select-option>
                    </a-select>
                </a-col>
                <a-col :span="4">
                    <a-button @click="resetFilters">重置筛选</a-button>
                </a-col>
            </a-row>
        </div>

        <!-- 作业列表 -->
        <div class="assignment-table">
            <a-table :columns="columns" :data-source="filteredAssignments" :pagination="pagination" :loading="loading"
                row-key="id">
                <template #bodyCell="{ column, record }">
                    <template v-if="column.key === 'course'">
                        <a-tag color="blue">{{ record.course }}</a-tag>
                    </template>
                    <template v-else-if="column.key === 'status'">
                        <a-tag :color="getStatusColor(record.status)">{{ getStatusText(record.status) }}</a-tag>
                    </template>
                    <template v-else-if="column.key === 'submissionCount'">
                        <span>{{ record.submissionCount }}/{{ record.totalStudents }}</span>
                    </template>
                    <template v-else-if="column.key === 'averageScore'">
                        <span v-if="record.averageScore">{{ record.averageScore }}分</span>
                        <span v-else>-</span>
                    </template>
                    <template v-else-if="column.key === 'action'">
                        <a-space>
                            <a-button type="link" @click="editAssignment(record)">编辑</a-button>
                            <a-button type="link" @click="viewSubmissions(record)">查看提交</a-button>
                            <a-button type="link" @click="reviewAssignments(record)">批改作业</a-button>
                            <a-popconfirm title="确定要删除这个作业吗？" @confirm="deleteAssignment(record.id)">
                                <a-button type="link" danger>删除</a-button>
                            </a-popconfirm>
                        </a-space>
                    </template>
                </template>
            </a-table>
        </div>

        <!-- 添加/编辑作业弹窗 -->
        <a-modal v-model:open="showAddModal" :title="isEditing ? '编辑作业' : '添加作业'" width="800px" @ok="handleSubmit"
            @cancel="handleCancel">
            <a-form ref="formRef" :model="assignmentForm" :rules="formRules" layout="vertical">
                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-form-item label="作业标题" name="title">
                            <a-input v-model:value="assignmentForm.title" placeholder="请输入作业标题" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="所属课程" name="course">
                            <a-select v-model:value="assignmentForm.course" placeholder="选择课程">
                                <a-select-option value="ai">AI智能体开发实战</a-select-option>
                                <a-select-option value="vue">Vue3实战开发</a-select-option>
                                <a-select-option value="spring">SpringBoot微服务</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                </a-row>

                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-form-item label="开始时间" name="startTime">
                            <a-date-picker v-model:value="assignmentForm.startTime" show-time style="width: 100%"
                                placeholder="选择开始时间" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="截止时间" name="endTime">
                            <a-date-picker v-model:value="assignmentForm.endTime" show-time style="width: 100%"
                                placeholder="选择截止时间" />
                        </a-form-item>
                    </a-col>
                </a-row>

                <a-form-item label="作业描述" name="description">
                    <a-textarea v-model:value="assignmentForm.description" :rows="4" placeholder="请输入作业描述和要求" />
                </a-form-item>

                <a-form-item label="作业内容" name="content">
                    <a-textarea v-model:value="assignmentForm.content" :rows="6" placeholder="请输入具体的作业内容" />
                </a-form-item>

                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-form-item label="满分" name="maxScore">
                            <a-input-number v-model:value="assignmentForm.maxScore" :min="0" :max="100"
                                style="width: 100%" placeholder="请输入满分" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="状态" name="status">
                            <a-select v-model:value="assignmentForm.status" placeholder="选择状态">
                                <a-select-option value="draft">草稿</a-select-option>
                                <a-select-option value="active">进行中</a-select-option>
                                <a-select-option value="completed">已结束</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                </a-row>

                <a-form-item label="AI自动批改" name="autoGrade">
                    <a-switch v-model:checked="assignmentForm.autoGrade" />
                    <span style="margin-left: 8px">启用AI自动批改</span>
                </a-form-item>
            </a-form>
        </a-modal>

        <!-- AI生成作业弹窗 -->
        <a-modal v-model:open="showAIModal" title="AI智能生成作业" width="600px" @ok="handleAIGenerate"
            @cancel="showAIModal = false">
            <a-form layout="vertical">
                <a-form-item label="选择课程">
                    <a-select v-model:value="aiForm.course" placeholder="选择要生成作业的课程">
                        <a-select-option value="ai">AI智能体开发实战</a-select-option>
                        <a-select-option value="vue">Vue3实战开发</a-select-option>
                        <a-select-option value="spring">SpringBoot微服务</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="作业类型">
                    <a-select v-model:value="aiForm.type" placeholder="选择作业类型">
                        <a-select-option value="practice">练习题</a-select-option>
                        <a-select-option value="project">项目作业</a-select-option>
                        <a-select-option value="exam">考试题</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="难度等级">
                    <a-select v-model:value="aiForm.difficulty" placeholder="选择难度">
                        <a-select-option value="easy">简单</a-select-option>
                        <a-select-option value="medium">中等</a-select-option>
                        <a-select-option value="hard">困难</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="生成数量">
                    <a-input-number v-model:value="aiForm.count" :min="1" :max="10" style="width: 100%"
                        placeholder="生成作业数量" />
                </a-form-item>
                <a-form-item label="特殊要求">
                    <a-textarea v-model:value="aiForm.requirements" :rows="3" placeholder="请输入特殊要求（可选）" />
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import {
    PlusOutlined,
    RobotOutlined,
    FileTextOutlined,
    ClockCircleOutlined,
    CheckCircleOutlined,
    TrophyOutlined
} from '@ant-design/icons-vue'
import type { FormInstance } from 'ant-design-vue'

// 响应式数据
const loading = ref(false)
const searchKeyword = ref('')
const selectedCourse = ref('')
const selectedStatus = ref('')
const showAddModal = ref(false)
const showAIModal = ref(false)
const isEditing = ref(false)
const formRef = ref<FormInstance>()

// 统计数据
const statistics = reactive({
    totalAssignments: 25,
    pendingReview: 8,
    completed: 17,
    averageScore: 85.6
})

// 作业表单
const assignmentForm = reactive({
    id: null,
    title: '',
    course: '',
    startTime: null,
    endTime: null,
    description: '',
    content: '',
    maxScore: 100,
    status: 'draft',
    autoGrade: true
})

// AI生成表单
const aiForm = reactive({
    course: '',
    type: '',
    difficulty: '',
    count: 1,
    requirements: ''
})

// 表单验证规则
const formRules = {
    title: [{ required: true, message: '请输入作业标题' }],
    course: [{ required: true, message: '请选择所属课程' }],
    startTime: [{ required: true, message: '请选择开始时间' }],
    endTime: [{ required: true, message: '请选择截止时间' }],
    description: [{ required: true, message: '请输入作业描述' }],
    content: [{ required: true, message: '请输入作业内容' }],
    maxScore: [{ required: true, message: '请输入满分' }]
}

// 分页配置
const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number) => `共 ${total} 条记录`
})

// 表格列配置
const columns = [
    {
        title: '作业标题',
        dataIndex: 'title',
        key: 'title',
        width: 200
    },
    {
        title: '所属课程',
        dataIndex: 'course',
        key: 'course',
        width: 150
    },
    {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        width: 100
    },
    {
        title: '开始时间',
        dataIndex: 'startTime',
        key: 'startTime',
        width: 150
    },
    {
        title: '截止时间',
        dataIndex: 'endTime',
        key: 'endTime',
        width: 150
    },
    {
        title: '提交情况',
        dataIndex: 'submissionCount',
        key: 'submissionCount',
        width: 120
    },
    {
        title: '平均分',
        dataIndex: 'averageScore',
        key: 'averageScore',
        width: 100
    },
    {
        title: '操作',
        key: 'action',
        width: 250,
        fixed: 'right'
    }
]

// 作业数据
const assignments = reactive([
    {
        id: 1,
        title: 'AI基础概念作业',
        course: 'AI智能体开发实战',
        status: 'active',
        startTime: '2024-01-15 00:00',
        endTime: '2024-01-20 23:59',
        submissionCount: 45,
        totalStudents: 50,
        averageScore: 88.5,
        description: '完成AI基础概念的学习和练习',
        content: '请回答以下问题：1. 什么是人工智能？2. 机器学习的基本原理是什么？',
        maxScore: 100,
        autoGrade: true
    },
    {
        id: 2,
        title: 'Vue3组件开发作业',
        course: 'Vue3实战开发',
        status: 'completed',
        startTime: '2024-01-10 00:00',
        endTime: '2024-01-15 23:59',
        submissionCount: 38,
        totalStudents: 40,
        averageScore: 92.3,
        description: '使用Vue3开发一个组件',
        content: '开发一个可复用的表单组件，支持多种输入类型',
        maxScore: 100,
        autoGrade: false
    },
    {
        id: 3,
        title: 'SpringBoot项目实战',
        course: 'SpringBoot微服务',
        status: 'draft',
        startTime: '2024-01-25 00:00',
        endTime: '2024-01-30 23:59',
        submissionCount: 0,
        totalStudents: 30,
        averageScore: null,
        description: '完成一个SpringBoot微服务项目',
        content: '设计并实现一个用户管理系统',
        maxScore: 100,
        autoGrade: true
    }
])

// 计算属性
const filteredAssignments = computed(() => {
    return assignments.filter(assignment => {
        const keywordMatch = !searchKeyword.value ||
            assignment.title.toLowerCase().includes(searchKeyword.value.toLowerCase())
        const courseMatch = !selectedCourse.value || assignment.course.includes(selectedCourse.value)
        const statusMatch = !selectedStatus.value || assignment.status === selectedStatus.value

        return keywordMatch && courseMatch && statusMatch
    })
})

// 方法
const handleSearch = () => {
    console.log('搜索:', searchKeyword.value)
}

const handleCourseChange = () => {
    console.log('课程筛选:', selectedCourse.value)
}

const handleStatusChange = () => {
    console.log('状态筛选:', selectedStatus.value)
}

const resetFilters = () => {
    searchKeyword.value = ''
    selectedCourse.value = ''
    selectedStatus.value = ''
}

const editAssignment = (assignment: any) => {
    isEditing.value = true
    Object.assign(assignmentForm, assignment)
    showAddModal.value = true
}

const viewSubmissions = (assignment: any) => {
    console.log('查看提交:', assignment.title)
}

const reviewAssignments = (assignment: any) => {
    console.log('批改作业:', assignment.title)
}

const deleteAssignment = (id: number) => {
    const index = assignments.findIndex(assignment => assignment.id === id)
    if (index > -1) {
        assignments.splice(index, 1)
    }
    console.log('删除作业:', id)
}

const generateAIAssignment = () => {
    showAIModal.value = true
}

const handleAIGenerate = () => {
    console.log('AI生成作业:', aiForm)
    // 模拟AI生成作业
    const newAssignment = {
        id: Date.now(),
        title: `AI生成的${aiForm.type}作业`,
        course: aiForm.course === 'ai' ? 'AI智能体开发实战' :
            aiForm.course === 'vue' ? 'Vue3实战开发' : 'SpringBoot微服务',
        status: 'draft',
        startTime: new Date().toISOString().split('T')[0] + ' 00:00',
        endTime: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0] + ' 23:59',
        submissionCount: 0,
        totalStudents: 30,
        averageScore: null,
        description: 'AI自动生成的作业',
        content: '根据AI分析生成的作业内容',
        maxScore: 100,
        autoGrade: true
    }
    assignments.unshift(newAssignment)
    showAIModal.value = false
}

const handleSubmit = async () => {
    try {
        await formRef.value?.validate()

        if (isEditing.value) {
            // 编辑作业
            const index = assignments.findIndex(assignment => assignment.id === assignmentForm.id)
            if (index > -1) {
                Object.assign(assignments[index], assignmentForm)
            }
        } else {
            // 添加作业
            const newAssignment = {
                ...assignmentForm,
                id: Date.now(),
                startTime: new Date().toISOString().split('T')[0] + ' 00:00',
                endTime: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0] + ' 23:59',
                submissionCount: 0,
                totalStudents: 30,
                averageScore: null
            }
            assignments.unshift(newAssignment)
        }

        showAddModal.value = false
        resetForm()
    } catch (error) {
        console.error('表单验证失败:', error)
    }
}

const handleCancel = () => {
    showAddModal.value = false
    resetForm()
}

const resetForm = () => {
    Object.assign(assignmentForm, {
        id: null,
        title: '',
        course: '',
        startTime: null,
        endTime: null,
        description: '',
        content: '',
        maxScore: 100,
        status: 'draft',
        autoGrade: true
    })
    isEditing.value = false
}

const getStatusColor = (status: string) => {
    const colors = {
        'active': 'green',
        'completed': 'blue',
        'draft': 'orange'
    }
    return colors[status as keyof typeof colors] || 'default'
}

const getStatusText = (status: string) => {
    const texts = {
        'active': '进行中',
        'completed': '已结束',
        'draft': '草稿'
    }
    return texts[status as keyof typeof texts] || status
}
</script>

<style scoped>
.assignment-management {
    padding: 0;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
}

.page-header h1 {
    margin: 0;
    color: #333;
}

.stats-cards {
    margin-bottom: 24px;
}

.search-section {
    background: #f5f5f5;
    padding: 16px;
    border-radius: 8px;
    margin-bottom: 16px;
}

.assignment-table {
    background: #fff;
    border-radius: 8px;
}
</style>